/**
 * tjftp -- A simple FTP server, using the ANSI C
 * Copyright (C) 2011  degui.chen <degui.chen@qq.com>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "cmd.h"
#include "../sesstion.h"
#include "../lib/port.h"
#include "../lib/sockets.h"
int tj_cmd_retr(int accept_fd, char* request, char* response) {
	request = request + strlen("RETR ");
	tj_string_trim(request);
	PSesstion sesstion = tj_sesstion_get(accept_fd);
	if (sesstion->is_port_mode) {
		char filepath[255] = { '\0' };
		sprintf(filepath, "%s%s/%s", sesstion->root_path, sesstion->pwd, request);
		char info[1024] = { '\0' };
		//@todo 添加文件是否存在的判断
		//@todo 添加权限的判断
		//@todo 重构成一个方法
		char ip[255] = { '\0' };
		strcpy(ip, sesstion->port_address);
		int port = tj_port_get_client_port(ip);
		memset(ip, '\0', 255);
		tj_port_get_ip_from_address(sesstion->port_address, ip);
		int fd = tj_create_tcp_socket();
		tj_tcp_open_connect(fd, ip, port);
		tj_tcp_send_file(fd, filepath);
		tj_sockets_close(fd);
	}
	//@todo pasv 模式的请求
	char info2[255] = {'\0'};
	sprintf(info2, "150 Opening BINARY mode data connection for %s (1044 bytes).\r\n", request);
	send(accept_fd, info2, strlen(info2) + 1, 0);

	strcpy(response, "226 Transfer complete.");
	return strlen(response);
}

/**
 * 经验：
 */
